﻿
using System;
using System.Linq;
using Microsoft.Phone.Shell;

namespace Phone.Framework
{
    /// <summary>
    /// Extensions to the <see cref="IApplicationBar"/>.
    /// </summary>
    public static class ApplicationBarExtensions
    {
        ///<summary>
        /// Finds an <see cref="ApplicationBarIconButton"/> by its name.
        ///</summary>
        ///<param name="appBar"></param>
        ///<param name="text"></param>
        ///<returns></returns>
        [CLSCompliant(false)]
        public static ApplicationBarIconButton FindButton(this IApplicationBar appBar, string text)
        {
            if (appBar == null) throw new ArgumentNullException("appBar");
            return (from object button in appBar.Buttons select button as ApplicationBarIconButton).FirstOrDefault(btn => btn != null && btn.Text == text);
        }

        public static void SwitchButtonIcon(this IApplicationBar appBar, 
            string text,Func<bool> condition,string trueIcon,string falseIcon)
        {
            var btn = FindButton(appBar, text);
            if (condition())
            {
                btn.IconUri = new Uri(trueIcon, UriKind.RelativeOrAbsolute);
            }
            else
            {
                btn.IconUri = new Uri(falseIcon, UriKind.RelativeOrAbsolute);
            }
        }

        ///<summary>
        /// Finds an <see cref="ApplicationBarIconButton"/> by its name.
        ///</summary>
        ///<param name="appBar"></param>
        ///<param name="text"></param>
        ///<returns></returns>
        [CLSCompliant(false)]
        public static ApplicationBarMenuItem FindMenuItem(this IApplicationBar appBar, string text)
        {
            if (appBar == null) throw new ArgumentNullException("appBar");
            return (from object button in appBar.MenuItems select button as ApplicationBarMenuItem).FirstOrDefault(btn => btn != null && btn.Text == text);
        }
    }
}
